package com.lagou.handle;

import com.lagou.pojo.RpcRequest;
import com.lagou.service.IUserService;
import com.lagou.service.UserServiceImpl;
import com.lagou.util.BeanUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class UserServiceHandle2 extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        if ((obj instanceof RpcRequest)) {
            RpcRequest rpcRequest = (RpcRequest) obj;
            String className = rpcRequest.getClassName();
            Class<?> aClass = Class.forName(className);
            Object bean = BeanUtil.getBean(aClass);

            //获取调用的方法名
            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Method method = aClass.getDeclaredMethod(methodName, parameterTypes);

            //执行方法
            Object[] parameters = rpcRequest.getParameters();
            Object result = method.invoke(bean, parameters);
            ctx.writeAndFlush(result);
        }
    }
}
